<?php
namespace services\models;

/**
 * 调价单
 *
 * @author huipeng.teng@liketry.com
 */
class WmsChangePrice extends \yii\db\ActiveRecord {

    /**
     * 执行调价（生效的调价单更新价格，失效的调价单还原价格。）
     */
    public static function run($count = 5000) {
        $now = date('Y-m-d H:i:s');

        // 单据状态为“审核”，没有执行过调价的单据，并且当前时间在单据的活动时间范围内，则进行调价操作。
        $update_rows = self::getDb()
                ->createCommand("SELECT wms_change_price_id FROM d_try.wms_change_price "
                        . "WHERE STATUS = 2 AND is_exec = 0 AND start_time <= '" . $now . "' AND '" . $now . "' <= end_time "
                        . "LIMIT " . $count)
                ->queryAll();

        if(!empty($update_rows)) {
            foreach($update_rows as $row) {
                self::updatePrice($row['wms_change_price_id']);
            }
            unset($update_rows);
        }

        // 单据状态为“审核”，并且结束时间小于当前时间，则进行终止操作。
        $revert_rows = self::getDb()
                ->createCommand("SELECT wms_change_price_id,is_exec FROM d_try.wms_change_price "
                        . "WHERE status = 2 AND end_time < '" . $now 
                        . "' LIMIT " . $count)
                ->queryAll();

        if(!empty($revert_rows)) {
            foreach($revert_rows as $row) {
                // 已经执行过调价的，则还原价格类型和价格。
                if($row['is_exec'] == 1) {
                    self::revertPrice($row['wms_change_price_id']);
                }

                // 调价单的状态修改为“终止”
                self::getDb()->createCommand()->update('d_try.wms_change_price', ['status' => 4], 'wms_change_price_id = ' . $row['wms_change_price_id'])->execute();
            }
            unset($revert_rows);
        }
    }

    /**
     * 获取主从数据库的连接
     */
    public static function getDb() {
        return \Yii::$app->db;
    }

    /**
     * 获取商品的Redis连接
     */
    private static function getRedisGoods() {
        return \Yii::$app->redis_goods;
    }

    /**
     * 获取从数据库的连接
     */
    private static function getSlaveDb() {
        return \Yii::$app->db;
    }

    /**
     * 还原某个单据的商品调价信息
     * @param int $wms_change_price_id 调价单ID
     */
    private static function revertPrice($wms_change_price_id) {
        $goods_rows = self::getDb()->createCommand('SELECT goods_id,product_id,price_type_old,price_old '
                . 'FROM d_try.wms_change_price_goods '
                . 'WHERE wms_change_price_id = ' . $wms_change_price_id . ' AND is_delete = 0')
                ->queryAll();

        if(empty($goods_rows)) {
            return false;
        }

        foreach($goods_rows as $row) {
            $dataArray = array();
            if($row['price_type_old'] == 0) {
                $dataArray['sale_price'] = $row['price_old'];
            } elseif($row['price_type_old'] == 1) {
                $dataArray['try_price'] = $row['price_old'];
            }
            $dataArray['price_type'] = $row['price_type_old'];

            // 更新SKU的价格类型和价格
            $affected_rows = self::getDb()->createCommand()->update('d_try.product', $dataArray, 'product_id = ' . $row['product_id'])->execute();

            if($affected_rows > 0) {
                // 更新Redis
                self::getRedisGoods()->hmset('product_' . $row['product_id'], $dataArray);
                Goods::deleteRedisById($row['goods_id']);
            }
        }
        unset($goods_rows);

        $goods_list = self::getDb()->createCommand('SELECT DISTINCT goods_id '
                . 'FROM d_try.wms_change_price_goods '
                . 'WHERE wms_change_price_id = ' . $wms_change_price_id . ' AND is_delete = 0')
                ->queryAll();

        if(!empty($goods_list)) {
            foreach($goods_list as $row) {
                $this->updateGoodsPrice($row['goods_id']);
            }
            unset($goods_list);
        }
    }

    /**
     * 立即更新某个单据的商品调价信息
     * @param int $wms_change_price_id 调价单ID
     */
    private static function updatePrice($wms_change_price_id) {
        $goods_rows = self::getDb()->createCommand('SELECT goods_id,product_id,price_type_new,price_new '
                . 'FROM d_try.wms_change_price_goods '
                . 'WHERE wms_change_price_id = ' . $wms_change_price_id . ' AND is_delete = 0')
                ->queryAll();

        if(empty($goods_rows)) {
            // 更新调价单的执行状态为“已执行”
            self::getDb()->createCommand()->update('d_try.wms_change_price', ['is_exec' => 1], 'wms_change_price_id = ' . $wms_change_price_id)->execute();
            return false;
        }

        foreach($goods_rows as $row) {
            $dataArray = array();
            if($row['price_type_new'] == 0) {
                $dataArray['sale_price'] = $row['price_new'];
            } elseif($row['price_type_new'] == 1) {
                $dataArray['try_price'] = $row['price_new'];
            }
            $dataArray['price_type'] = $row['price_type_new'];

            // 更新SKU的价格类型和价格
            $affected_rows = self::getDb()->createCommand()->update('d_try.product', $dataArray, 'product_id = ' . $row['product_id'])->execute();

            if($affected_rows > 0) {
                // 更新Redis
                self::getRedisGoods()->hmset('product_' . $row['product_id'], $dataArray);
                Goods::deleteRedisById($row['goods_id']);
            }
        }
        unset($goods_rows);

        // 更新调价单的执行状态为“已执行”
        self::getDb()->createCommand()->update('d_try.wms_change_price', ['is_exec' => 1], 'wms_change_price_id = ' . $wms_change_price_id)->execute();

        // 更新商品的价格
        $goods_list = self::getDb()->createCommand('SELECT DISTINCT goods_id '
                . 'FROM d_try.wms_change_price_goods '
                . 'WHERE wms_change_price_id = ' . $wms_change_price_id . ' AND is_delete = 0')
                ->queryAll();

        if(!empty($goods_list)) {
            foreach($goods_list as $row) {
                $this->updateGoodsPrice($row['goods_id']);
            }
            unset($goods_list);
        }
    }

    /**
     * 用默认SKU的价格更新商品价格，如果没有设置默认SKU（数据异常情况），则用第一个SKU的价格更新商品的价格。
     * @param int $goods_id 商品ID
     */
    private function updateGoodsPrice($goods_id) {
        $product_rows = self::getDb()->createCommand('SELECT * FROM d_try.product '
                . 'WHERE goods_id = ' . $goods_id . ' AND status = 0 '
                . 'ORDER BY default_sku DESC, product_id ASC LIMIT 2')
                ->queryAll();

        if(empty($product_rows)) {
            return false;
        }

        $dataArray = array();
        foreach($product_rows as $row) {
            // 试用类型SKU
            if($row['type'] == 1) {
                $dataArray['try_price_rmb'] = $row['sale_price'];
                $dataArray['try_price_score'] = $row['try_price'];
                $dataArray['try_price_type'] = $row['price_type'];
            }
            // 购买类型SKU
            if($row['type'] == 2) {
                $dataArray['sale_price_rmb'] = $row['sale_price'];
                $dataArray['sale_price_score'] = $row['try_price'];
                $dataArray['sale_price_type'] = $row['price_type'];
            }
        }
        unset($product_rows);

        $affected_rows = self::getDb()->createCommand()->update('d_try.goods_price', $dataArray, 'goods_id = ' . $goods_id)->execute();
        if($affected_rows > 0) {
            self::getRedisGoods()->hmset('goods_' . $goods_id, $dataArray);
        }
    }
}
